<template>
  <Card style="width: 100%" title="角色管理">
    <!-- 查询表单区 -->
    <div class="form-area">
      <Form
        name="form"
        ref="formRef"
        :labelCol="{ span: 5, offset: 0 }"
        @finish="formFinish"
        :initialValues="initQueryForm"
      >
        <Row :gutter="16">
          <Col :span="8">
            <FormItem name="roleName" label="角色名称" initialValue="">
              <Input
                placeholder="请输入角色名称"
                style="width: 70%"
                allowClear
              />
            </FormItem>
          </Col>
          <Col :span="8">
            <FormItem name="status" label="角色状态" initialValue="" style="position: relative;" class="selectPosition">
              <Select
                placeholder="请选择角色状态"
                style="width: 70%"
                allowClear
                :getPopupContainer="getPopupContainer"
              >
                <Option
                  v-for="type in dict.type.sys_normal_disable"
                  :key="type.value"
                  :label="type.label"
                  :value="type.value"
                ></Option>
              </Select>
            </FormItem>
          </Col>
          <Col :span="8">
            <FormItem :wrapperCol="{ span: 20, offset: 5 }">
              <Button type="primary" @click="handleQuery">
                <Icon
                  name="search"
                  style="margin-top: 3px; margin-right: 5px"
                />
                查 询
              </Button>
              <Button style="margin-left: 10px" @click="formReset">
                <Icon
                  name="rollback-outline"
                  style="margin-top: 3px; margin-right: 5px"
                />
                重 置
              </Button>
              <!-- <Button type="link" style="color: #b30000">更多 <Icon name="down" style="vertical-align: middle" /></Button> -->
            </FormItem>
          </Col>
        </Row>
      </Form>
    </div>

    <!-- 分割线 -->
    <Divider />
    <div class="button-area">
      <Button type="primary" @click="clickAdd()">
        <Icon name="add" /> 新增
      </Button>
    </div>
    <Skeleton
      :loading="loading"
      :avatar="false"
      active
      :paragraph="{ rows: 6 }"
    >
      <Table
        :columns="columns"
        :dataSource="dataList"
        :bordered="false"
        @change="handleTableChange"
        :pagination="{
          total: total,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSize: queryParams.pageSize,
          current: queryParams.pageNum,
        }"
      >
        <template #render="render">
          <div v-if="render.dataIndex == 'status'">
            <dict-tag
              :options="dict.type.sys_normal_disable"
              :value="render.record.status"
            />
          </div>
          <div v-else-if="render.dataIndex == 'operation'">
            <a href="#" @click.prevent="tblOptForm(render.record)">
              <Icon name="edit" style="margin-top: 4px" />编辑
            </a>
            <a
              href="#"
              @click.prevent="
                deleteClick(render.record.roleId, render.record.roleName)
              "
            >
              <Icon name="delete-can" style="margin-top: 4px" />删除
            </a>
          </div>
        </template>
        <template #paginationTotal="props">
          <span>总共{{ props.total }} 条</span>
        </template>
      </Table>
    </Skeleton>
    <!-- 表单页对话框 -->
    <Modal
      class="fromModal"
      v-if="formDialogInfo.visible"
      :title="formDialogInfo.title"
      v-model="formDialogInfo.visible"
      @cancel="formDialogInfo.visible = false"
      width="800px"
      :bodyStyle="{ padding: '0px' }"
      :footer="[null]"
    >
      <modal-form
        :key="Date.now()"
        :id="formDialogInfo.id"
        :currentRow="formDialogInfo.currentRow"
        @handleCancel="formDialogCancel"
      ></modal-form>
    </Modal>
  </Card>
</template>

<script>
import {
  listRole,
  getRole,
  delRole,
  addRole,
  updateRole,
  dataScope,
  changeRoleStatus,
} from "@/api/system/role";
import {
  treeselect as menuTreeselect,
  roleMenuTreeselect,
} from "@/api/system/menu";
import ModalForm from "./components/ModalFormRole.vue";
import { Message, Modal } from "@uni/vue";
export default {
  dicts: ["sys_normal_disable"],
  components: {
    "modal-form": ModalForm,
  },
  data() {
    return {
      labelCol: {
        span: 6,
      },
      loading: true,
      wrapperCol: {
        span: 16,
      },
      initQueryForm: {
        roleName: "",
        status: "",
      },
      dataList: [],
      columns: [
        // {
        //   title: "角色编号",
        //   align: "center",
        //   dataIndex: "roleId",
        //   key: "roleId",
        // },
        {
          title: "角色名称",
          align: "center",
          dataIndex: "roleName",
          key: "roleName",
        },
        {
          title: "权限字符",
          align: "center",
          dataIndex: "roleKey",
          key: "roleKey",
        },

        {
          title: "显示顺序",
          align: "center",
          dataIndex: "roleSort",
          key: "roleSort",
        },
        {
          title: "状态",
          align: "center",
          dataIndex: "status",
          key: "status",
        },
        {
          title: "创建时间",
          align: "center",
          dataIndex: "createTime",
          key: "createTime",
        },
        {
          title: "操作",
          align: "center",
          dataIndex: "operation",
          key: "operation",
        },
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roleName: null,
        status: null,
      },
      total: 0,
      formDialogInfo: {
        title: "",
        visible: false,
        id: "",
        currentRow: {},
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getPopupContainer() {
      return document.querySelector(".selectPosition")
    },
    async clickAdd() {
      (this.formDialogInfo = {
        title: "添加角色",
        visible: false,
        id: "",
        currentRow: {},
      }),
        (this.formDialogInfo.visible = true);
    },
    async tblOptForm(row) {
      this.formDialogInfo.title = "修改用户";
      this.formDialogInfo.id = row.roleId;
      this.formDialogInfo.currentRow = row;
      await this.getRoleMenuTreeselect(row.roleId);
      this.formDialogInfo.visible = true;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.$refs.formRef.submit();
    },
    formFinish(formValues) {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        roleName: formValues.roleName,
        status: formValues.status,
      };
      this.getList();
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      listRole(this.queryParams).then((response) => {
        if (response.code == 200) {
          this.dataList = response.rows;
          this.dataList.map((item) => {
            // if(item.dept)
            // item.deptName = item.dept.deptName;
          });
          this.total = response.total;
          this.loading = false;
        } else {
          Message.error({ text: "获取信息失败：" + response.msg });
        }
      });
    },
    getRoleMenuTreeselect(roleId) {
      let that = this;
      return roleMenuTreeselect(roleId).then((response) => {
        let menuTree = response.menus.map((org) => that.mapTree(org));
        let checkKey = response.checkedKeys.map((org) => String(org));
        this.formDialogInfo.currentRow.menuOptions = menuTree;
        this.formDialogInfo.currentRow.menuIds = checkKey;
        return response;
      });
    },
    mapTree(org) {
      const haveChildren =
        Array.isArray(org.children) && org.children.length > 0;
      if (haveChildren) {
        return {
          title: org.label,
          value: String(org.id),
          children: org.children.map((i) => this.mapTree(i)),
        };
      } else {
        return {
          title: org.label,
          value: String(org.id),
        };
      }
    },
    handleTableChange(p, filters) {
      const { current, pageSize } = p;
      this.queryParams.pageNum = current;
      this.queryParams.pageSize = pageSize;
      this.getList();
    },
    formReset(value) {
      console.log(value);
      this.$refs.formRef.reset();
    },
    formDialogCancel() {
      this.formDialogInfo.visible = false;
      this.getList();
    },
    // 角色状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "停用" : "启用";
      Modal.confirm({
        title: "改变状态？",
        content: '确认要"' + text + '""' + row.userName + '"用户吗？',
        onOk: () => {
          row.status = row.status === "0" ? "1" : "0";
          changeUserStatus(row.userId, row.status)
            .then(() => {
              Message.success({ text: text + "成功" });
              this.getList();
            })
            .catch(function () {
              row.status = row.status === "0" ? "1" : "0";
            });
        },
        onCancel: () => {},
      });
    },
    /** 删除按钮操作 */
    deleteClick(id, name) {
      this.$MessageBox.ModalConfirm(
        '是否确认删除名称为"' + name + '"的数据项？',
        () => {
          delRole(id).then(() => {
            this.getList();
            Message.success({ text: "删除成功" });
            done();
          });
        }
      );
    },
  },
};
</script>
<style scoped lang="scss">
/* 弹框区 */
::v-deep
  .fromModal
  > .uni-modal-wrap
  > .uni-modal-wrap-content
  > .uni-modal-footer {
  padding: 0;
}
/* 查询表单区 */
.form-area {
  /* background-color: lightcyan; */
  margin-top: 15px;
  margin-left: 50px;
  margin-right: 50px;
}

.uni-divider {
  margin: 0;
}
/* 按钮区 */
::v-deep .button-area {
  margin: 20px 0 8px;
  .uni-btn-inner {
    display: flex;
    align-items: center;
  }
  /* background-color: lightcyan; */
}
.button-area svg {
  margin-right: 5px;
}
</style>


